package reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reggie.dto.DishDto;
import reggie.entity.Dish;
import reggie.entity.DishFlavor;
import reggie.mapper.DishMapper;
import reggie.service.DishFlavorService;
import reggie.service.DishService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: DishServiceImpl <br/>
 * Description: <br/>
 * date: 2022/12/1 22:00<br/>
 *
 * @author Xingyingsheng<br />
 * @since JDK 11
 */
@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;

    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
//        保存菜品的基本信息到菜品表中
        this.save(dishDto);
//        给口味附上菜品的ID再保存
        Long dishID = dishDto.getId();

        List<DishFlavor> flavors = dishDto.getFlavors();
            flavors.stream().map((item) -> {
            item.setDishId(dishID);
            return item;
        }).collect((Collectors.toList()));

//        保存菜品口味
        dishFlavorService.saveBatch(flavors);

    }

    @Override
    public DishDto getByIdWithFlavor(Long id) {
//        查询基本信息从dish表中
        Dish dish = this.getById(id);
//        查询当前菜品对应的口味信息，从dish_flacor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
//      给数据复制值和添加值
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
//        更新dish表基本信息
        this.updateById(dishDto);
//          清理当前菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
//        添加当前提交过来的口味
        List<DishFlavor> flavors = dishDto.getFlavors();
//        还要给口味添加上菜品id
        flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect((Collectors.toList()));
        dishFlavorService.saveBatch(flavors);
    }


}
